package com.magist.manage.web.controller;

import com.github.pagehelper.PageInfo;
import com.magist.core.controller.BaseController;
import com.magist.core.entity.CxtHolder;
import com.magist.core.entity.ResultMessage;
import com.magist.core.enums.UserTypeEnum;
import com.magist.core.exception.BusinessException;
import com.magist.core.util.BeanCopyUtil;
import com.magist.core.util.MAssertUtil;
import com.magist.core.util.TxtUtil;
import com.magist.manage.enums.TFEnum;
import com.magist.manage.web.dto.UserAuthDto;
import com.magist.manage.web.dto.UserInfoDto;
import com.magist.manage.web.entity.UserAuth;
import com.magist.manage.web.entity.UserInfo;
import com.magist.manage.web.entity.UserLogin;
import com.magist.manage.web.facade.UserFacade;
import com.magist.manage.web.service.UserAuthService;
import com.magist.manage.web.service.UserInfoService;
import com.magist.manage.web.service.UserLoginService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.assertj.core.util.Lists;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

@Api(value = "用户信息", tags = {"用户信息接口"})
@RestController
@RequestMapping("/rest/userInfo")
public class RestUserInfoController extends BaseController {

    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private UserLoginService userLoginService;
    @Autowired
    private UserFacade userFacade;
    @Autowired
    private UserAuthService userAuthService;

    @ApiOperation(value = "保存", notes = "保存接口")
    @RequestMapping(value = "save.do", method = RequestMethod.POST)
    public Object save(@ModelAttribute("userInfoDto") UserInfoDto userInfoDto) {

        userFacade.addUser(userInfoDto);
        return ResultMessage.success();
    }

    @ApiOperation(value = "重置密码", notes = "重置密码接口")
    @RequestMapping(value = "resetPass.do", method = RequestMethod.POST)
    public Object resetPass(@ModelAttribute("userInfoDto") UserInfoDto userInfoDto) {
        UserInfo oldUserInfo = userInfoService.getById(userInfoDto.getId());
        if (oldUserInfo == null)
            throw new BusinessException("无效的数据!");
        Assert.hasLength(userInfoDto.getPassword(), "密码不能为空");
        UserLogin userLogin = userLoginService.getById(oldUserInfo.getId());
        ResultMessage result = null;
        userLogin.setPassword(TxtUtil.digest(userInfoDto.getPassword()));
        userLogin.setModifyTime(oldUserInfo.getModifyTime());
        if (userLoginService.update(userLogin) > 0) {
            result = ResultMessage.success("操作成功");
        } else
            result = ResultMessage.error("操作失败!");
        return result;
    }

    @ApiOperation(value = "更新", notes = "更新接口")
    @RequestMapping(value = "update.do", method = RequestMethod.POST)
    public Object update(@ModelAttribute("userInfoDto") UserInfoDto userInfoDto) {
        UserInfo oldUserInfo = userInfoService.getById(userInfoDto.getId());
        if (oldUserInfo == null)
            throw new BusinessException("无效的数据!");
        ResultMessage result = null;
        UserInfo userInfo = BeanCopyUtil.copy(userInfoDto, UserInfo.class);
        userInfo.setModifyTime(oldUserInfo.getModifyTime());
        if (userInfoService.update(userInfo) > 0) {
            // userLogin更新
            UserLogin userLogin = userLoginService.getById(userInfoDto.getId());
            userLogin.setTel(userInfoDto.getTel());
            userLogin.setEmail(userInfoDto.getEmail());
            userLoginService.update(userLogin);
            result = ResultMessage.success("操作成功");
        } else
            result = ResultMessage.error("操作失败!");
        return result;
    }

    @ApiOperation(value = "列表", notes = "分页查询接口")
    @RequestMapping(value = "page.do", method = RequestMethod.GET)
    public Object page(@ModelAttribute("userInfoDto") UserInfoDto userInfoDto) {
        ResultMessage result = ResultMessage.success();
        UserInfo userInfo = new UserInfo();
        BeanUtils.copyProperties(userInfoDto, userInfo);
        if(!StringUtils.isEmpty(userInfo.getUserName())) {
            userInfo.setUserName("%" +userInfo.getUserName()+"%");
        }
        UserInfo onlineUser = userInfoService.getById(CxtHolder.getUser().getUserId());
        if (UserTypeEnum.OP.getCode().equals(onlineUser.getUserType())) {
            userInfo.setId(onlineUser.getId());
        }

        PageInfo<UserInfo> pageInfo = userInfoService.page(userInfo, getPageInfo());
        List<UserInfo> list = pageInfo.getList();
        List<UserInfoDto> listDto = Lists.newArrayList();
        if (!CollectionUtils.isEmpty(list)) {
            for (UserInfo info : list) {
                UserInfoDto copyDto = BeanCopyUtil.copy(info, UserInfoDto.class);
                String userId = copyDto.getId();
                UserLogin userLogin = userLoginService.getById(userId);
                copyDto.setEmail(userLogin.getEmail());
                copyDto.setTel(userLogin.getTel());

                String roleGroupName = userAuthService.getRoleGroupNameByUserId(userId);
                copyDto.setRoleGroupName(roleGroupName);
                listDto.add(copyDto);
            }
            PageInfo<UserInfoDto> copyPage = BeanCopyUtil.copy(pageInfo, PageInfo.class);
            copyPage.setList(listDto);
            result.setContent(copyPage);
            return result;
        }
        result.setContent(pageInfo);
        return result;
    }

    @ApiOperation(value = "删除", notes = "删除接口")
    @RequestMapping(value = "del.do", method = RequestMethod.POST)
    public Object del(@ModelAttribute("id") String id) {
        UserInfo userInfo = userInfoService.getById(id);
        if (userInfo == null)
            throw new BusinessException("无效的数据!");
        ResultMessage result = null;
        if (userInfoService.delete(userInfo) > 0)
            result = ResultMessage.success("操作成功");
        else
            result = ResultMessage.error("操作失败!");
        return result;
    }

    @ApiOperation(value = "详情", notes = "详情接口")
    @RequestMapping(value = "info.do", method = RequestMethod.GET)
    public Object info(@ModelAttribute("id") String id) {
        UserInfo userInfo = userInfoService.getById(id);
        UserLogin userLogin = userLoginService.getById(id);
        if (userInfo == null)
            throw new BusinessException("无效的数据!");
        UserInfoDto userInfoDto = BeanCopyUtil.copy(userInfo, UserInfoDto.class);

        // userLogin更新
        userInfoDto.setTel(userLogin.getTel());
        userInfoDto.setEmail(userLogin.getEmail());
        userInfoDto.setLoginName(userLogin.getLoginName());
        userInfoDto.setPassword(userLogin.getPassword());
        ResultMessage result = ResultMessage.success();
        result.setContent(userInfoDto);
        return result;
    }

    @ApiOperation(value = "用户权限保存", notes = "用户权限保存接口")
    @RequestMapping(value = "authSaveOrUpdate.do", method = RequestMethod.POST)
    public Object authSaveOrUpdate(@ModelAttribute("userAuthDto") UserAuthDto userAuthDto) {
        MAssertUtil.notNull(userAuthDto.getId(),"用户id不能为空");

        UserAuth userAuth = userAuthService.getById(userAuthDto.getId());
        if (userAuth != null) {

            BeanUtils.copyProperties(userAuthDto, userAuth);
            userAuthService.update(userAuth);
        } else {
            userAuth = new UserAuth();
            BeanUtils.copyProperties(userAuthDto, userAuth);
            userAuthService.insert(userAuth);
        }

        return ResultMessage.success();
    }

    @ApiOperation(value = "用户权限详情", notes = "用户权限详情接口")
    @RequestMapping(value = "infoUserAuth.do", method = RequestMethod.GET)
    public Object infoUserAuth(@ModelAttribute("id") String id) {
        ResultMessage result = ResultMessage.success();
        UserAuth userAuth = userAuthService.getById(id);
        if (userAuth != null) {
            UserAuthDto userAuthDto = new UserAuthDto();
            BeanUtils.copyProperties(userAuth, userAuthDto);

            result.setContent(userAuthDto);
        }
        return result;
    }

    @ApiOperation(value="查询交接人列表", notes="查询交接人列表")
    @GetMapping("fetchAuthUserList.do")
    public Object fetchAuthUserList(@ModelAttribute("userId") String userId) {
        ResultMessage result = ResultMessage.success();
        if(StringUtils.isEmpty(userId)) {
            return result;
        }
        Example example = new Example(UserInfo.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andNotEqualTo("id", userId);
        criteria.andEqualTo("deleted", TFEnum.F.getCode());
        PageInfo<UserInfo> pageInfo = userInfoService.page(example, getPageInfo());
        List<UserInfo> list = pageInfo.getList();
        List<UserInfoDto> listDto = Lists.newArrayList();
        if (!CollectionUtils.isEmpty(list)) {
            for (UserInfo info : list) {
                UserInfoDto copyDto = BeanCopyUtil.copy(info, UserInfoDto.class);
                String userItemId = copyDto.getId();
                UserLogin userLogin = userLoginService.getById(userItemId);
                copyDto.setEmail(userLogin.getEmail());
                copyDto.setTel(userLogin.getTel());
                listDto.add(copyDto);
            }
            PageInfo<UserInfoDto> copyPage = BeanCopyUtil.copy(pageInfo, PageInfo.class);
            copyPage.setList(listDto);
            result.setContent(copyPage);
            return result;
        }
        result.setContent(pageInfo);
        return result;
    }

    @ApiOperation(value = "交接对接人", notes = "数据交接对接人")
    @RequestMapping(value = "doAuthUser.do", method = RequestMethod.POST)
    public Object doAuthUser(@ModelAttribute("userId") String userId,@ModelAttribute("authByUserId")String authByUserId) {
        userInfoService.doDataAuthUser(userId, authByUserId);
        ResultMessage result = ResultMessage.success();
        return result;
    }

}
